#include "port.h"

Port::Port()
{
  myLink = NULL;
  myActiveColor = Qt::blue;
  myInactiveColor = Qt::transparent;

  setFlags(ItemIsSelectable | ItemIsMovable);
  setAcceptHoverEvents(true);
}

Port::~Port()
{
   delete myLink;
}

void Port::addLink(Link * link)
{
  myLink = link;
}

void Port::removeLink(Link * /*link*/)
{
  myLink = NULL;
}

QRectF Port::outlineRect() const
{
  QRectF rect(0,0,WIDTH, HEIGHT);
  //rect.translate(-rect.center());
  return rect;
}

QRectF Port::boundingRect() const
{
  const int margin = 1;
  return outlineRect().adjusted(-margin, -margin, margin, margin);
}

QPainterPath Port::shape() const
{
  QRectF rect = outlineRect();
  
  QPainterPath path;
  path.addRoundRect(rect, roundness(rect.width()), roundness(rect.height()));
  return path;
}

void Port::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget* /*widget*/)
{
  if (!painter || !option) return;
 
  if ( option->state & QStyle::State_MouseOver ){
    painter->setBrush(myActiveColor); 
    painter->setPen(myActiveColor);
  } else {
    painter->setBrush(myInactiveColor);
    painter->setPen(myInactiveColor);
  }
  
  QRectF rect = outlineRect();
  painter->drawRoundRect(rect, roundness(rect.width()), roundness(rect.height()));
  
  QPointF fBeginP = rect.center();
  QPointF fPan(10,0);
  QPointF fEndP = fBeginP+fPan;
  QLineF portLine( fBeginP, fEndP);
  painter->drawLine(portLine);
  /* 
  painter->setPen(myTextColor);
  painter->drawText(rect, Qt::AlignCenter, myText);
  */
}

QVariant Port::itemChange(GraphicsItemChange change, const QVariant &value)
{
  if(change == ItemPositionHasChanged) {
      if (myLink)  myLink->trackNodes();
  }
  return QGraphicsItem::itemChange(change, value);
}

/*
void Port::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
  QString text = QInputDialog::getText(event->widget(), tr("Edit Text"), tr("Enter new text:"), QLineEdit::Normal, myText);

  if(!text.isEmpty()) setText(text);
} */

void Port::hoverEnterEvent(QGraphicsSceneMouseEvent * /*event*/)
{
  this->setSelected(true);
  //update();
}

void Port::hoverLeaveEvent(QGraphicsSceneMouseEvent * /*event*/)
{
  this->setSelected(false);
  //update();
}

int Port::roundness(double /*size*/) const
{
  //const int diameter = 12;
  //return 100 * diameter / int(size);
  return 0;
}

